#!/usr/bin/env node
const log = console.log, 
      fs = require('fs'),
      url =require('url'),
      http = require('http');


let chapterList = require('./data.js');
log(chapterList);


chapterList = chapterList.chapterList;
chapterList.sort((a,b)=>{
  let t1 = new Date(a.publishTimer);
  let t2 = new Date(b.publishTimer);
  return t2-t1;
});
log('/n')
log(chapterList);


function getPage(){
  let html = fs.readFileSync('./chapters.html');
  return html;
}

http.createServer((req,res)=>{
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
  
  
  if(req.url === '/'){
    res.end(getPage());

  }
  if(req.url === '/getlist'){
    res.end(JSON.stringify(chapterList));
  }
  if(req.url != '/' && req.url != '/getlist'){
    var uurl = '.'+req.url;
    var type = uurl.substr(uurl.lastIndexOf(".")+1,uurl.length)
    res.writeHead(200,{'Content-type':"text/"+type});
    fs.readFile(uurl, function(err, data) {
      if (err) {
        console.error(err);
        return;
      }
      res.end(data);
    })
  }


}).listen(8080);
  





